<script setup>
import MainContainer from '@/components/MainContainer.vue';
import { ref, watch } from 'vue';
import { useAdminStore } from '@/stores';
import { jobGetListByDeptId, editDeptName, addDept, delDept, addJob, delJobs } from '@/api/setting';
import { ElMessage } from 'element-plus';

const isConfirm = ref(false)
const drawer = ref(false)
const filterText = ref('')
const treeRef = ref('')
const adminStore = useAdminStore()
adminStore.getDeptCasList()
const jobList = ref([])
// 关键词送偶所
watch(filterText, val => {
  treeRef.value.filter(val)
})
const filterNode = (value, data) => {
  if (!value) return true
  return data.name.includes(value)
}
// 修改架构名称
const edit = (data) => {
  console.log(data)
  ElMessageBox.prompt('请输入2到10位架构名称', '修改架构名称', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    inputValue: data.label,
    inputPattern: /^[\u4E00-\u9FA5A-Za-z0-9_ ]{2,10}$/,// 数字、字符、汉字、空格、下划线，2-10个字符
    inputErrorMessage: '2-10位字符，支持数字、字符、汉字、空格、下划线'
  }).then(async ({ value }) => {
    await editDeptName(treeRef.value.currentNode.data.id, value).then(async (res) => {
      ElMessage.success(res.data.data)
      adminStore.getDeptCasList()
      console.log('修改完成')
    })
  }).catch(() => {
    ElMessage.warning('取消修改')
  })
  console.warn(data.label)
}
//新增组织架构（节点）
const append = (data) => {
  ElMessageBox.prompt('请输入2到10位架构名称', '新增架构名称', {
    confirmButtonText: '确定',
    cancelButtonText: '取消',
    inputValue: data.label,
    inputPattern: /^[\u4E00-\u9FA5A-Za-z0-9_ ]{2,10}$/,// 数字、字符、汉字、空格、下划线，2-10个字符
    inputErrorMessage: '2-10位字符，支持数字、字符、汉字、空格、下划线'
  }).then(async ({ value }) => {
    await addDept(data.id, value).then(async (res) => {
      ElMessage.success(res.data.data)
      adminStore.getDeptCasList()
      console.log('修改完成')
    })
  }).catch(() => {
    ElMessage.warning('取消修改')
  })
}
// 删除部门
const remove = async (data) => {
  if (data.children && data.children.length) {
    ElMessage.error('请先删除子节点')
    return
  }
  console.log(treeRef.value.currentNode.data.id)
  await delDept(treeRef.value.currentNode.data.id).then((res) => {
    if (res.data.success) {
      adminStore.getDeptCasList()
      ElMessage.success(res.data.data)
    }
  })
  isConfirm.value = false
}
//查询展示岗位数据
const showNodeData = async () => {
  // console.log(treeRef.value.currentNode.data.id)
  await jobGetListByDeptId(treeRef.value.currentNode.data.id).then(res => {
    jobList.value = res.data.data
  })
  console.log(jobList.value)
}
// 新增岗位
const jobDetail = ref({
  name: '',
  code: '',
  description: '',
  deptId: ''
})
const optionProps = ref({
  value: "id"
})
const doAddJob = async () => {
  await addJob(jobDetail.value).then(res => {
    console.log(res.data)
    ElMessage.success(res.data.data)
  })
  showNodeData()
  drawer.value = false
  jobDetail.value = {
    name: '',
    code: '',
    description: '',
    deptId: ''
  }
}
// 批量删除
const jobDelList = ref([])
const ids = ref([])
const handleSelectionChange = (value) => {
  ids.value = []
  console.log(value)
  value.forEach(element => {
    console.log(element.id)
    ids.value.push(element.id)
  });
  console.log(ids)
}
const jobsDel = async () => {
  console.log(ids.value)
  await delJobs(ids.value).then(res => {
    ElMessage.success(res.data.data)
    ids.value = []
    showNodeData()
  })
}
</script>

<template>
  <MainContainer ref="mainContainerRef" title="架构管理">
    <el-row class="main">
      <el-col :span="4" class="left">
        <p>公司架构</p>
        <el-input class="search" v-model="filterText" placeholder="关键词搜索" />
        <el-tree ref="treeRef" class="filter-tree" :props="{ children: 'children', label: 'name' }"
          :data="adminStore.deptList" node-key="id" default-expand-all :expand-on-click-node="false"
          :filter-node-method="filterNode" @node-click="showNodeData">
          <template #default="{ node, data }">
            <span class="custom-tree-node">
              <span>{{ node.label }}</span>
              <span>
                <a v-auth="['admin:structure:editDeptName']" @click="edit(data)"> <el-icon>
                    <Edit />
                  </el-icon> </a>
                <a v-auth="['admin:structure:addDept']" v-if="node.level < 3" style="margin-left: 8px"
                  @click="append(data)"> <el-icon>
                    <CirclePlusFilled />
                  </el-icon> </a>
                <a v-auth="['admin:structure:delDept']" style="margin-left: 8px" @click="isConfirm = true"> <el-icon>
                    <DeleteFilled />
                  </el-icon> </a>
                <!-- <a style="margin-left: 8px" @click="remove(data)"> <el-icon>
                    <DeleteFilled />
                  </el-icon> </a> -->
              </span>
            </span>
          </template>
        </el-tree>
      </el-col>
      <el-col :span="20" class="right">
        <el-row class="row1">
          <!-- <el-button class="btn" type="primary">新增岗位</el-button> -->
        </el-row>
        <el-row class="operate">
          <el-text>已选中{{ jobDelList.length }}项</el-text>
          <span class=blank></span>
          <span>
            <ul class="op-list">
              <el-link v-auth="['admin:structure:delDept']" @click="jobsDel"><el-icon color="red">
                  <Delete />
                </el-icon>批量删除</el-link>
              <el-button v-auth="['admin:structure:addJob']" class="btn" type="primary"
                @click="drawer = true">新增岗位</el-button>
            </ul>
          </span>
        </el-row>
        <el-table :data="jobList" @selection-change="handleSelectionChange">
          <el-table-column type="selection" width="55" align="center" label-align="center"></el-table-column>
          <el-table-column type="index" label="序号" width="100" align="center" label-align="center"></el-table-column>
          <el-table-column prop="name" label="岗位名称" align="center" label-align="center"></el-table-column>
          <el-table-column prop="code" label="岗位编号" width="100" align="center" label-align="center"></el-table-column>
          <el-table-column prop="description" label="备注" align="center" label-align="center"></el-table-column>
          <template #empty>
            <el-empty description="未查询到数据" />
          </template>
        </el-table>

      </el-col>
    </el-row>
    <!-- <el-dialog v-model="dialogVisible" title="提示" width="30%">
      <el-form :model="form" label-width="120px">
        <el-form-item label="部门名称">
          <el-input v-model="form.name" />
        </el-form-item>
        <el-form-item label="部门编号">
          <el-input v-model="form.code" />
        </el-form-item>
      </el-form>
    </el-dialog> -->
    <!-- 删除确认对话框 -->
    <el-dialog v-model="isConfirm" title="删除确认" width="500">
      <el-text type="danger"> 是否确认删除部门</el-text>
      <template #footer>
        <div>
          <el-button @click="isConfirm = false" type="primary">取消</el-button>
          <el-button @click="remove" type="danger">确认</el-button>
        </div>
      </template>
    </el-dialog>
    <!-- 新增岗位 -->
    <el-drawer v-model="drawer" direction="rtl" size="25%">
      <template #header>
        <h4>新增岗位</h4>
      </template>
      <template #default>
        <div>
          <el-form :model="jobDetail" label-width="auto" style="width: 90%; margin-left: 5%">
            <el-form-item label="岗位名称" required>
              <el-input v-model="jobDetail.name"></el-input>
            </el-form-item>
            <el-form-item label="岗位编号">
              <el-input v-model="jobDetail.code"></el-input>
            </el-form-item>
            <el-form-item label="备注">
              <el-input type="textarea" :model="jobDetail.description"></el-input>
            </el-form-item>
            <el-form-item label="归属部门" required>
              <el-tree-select v-model="jobDetail.deptId" :data="adminStore.deptList" :render-after-expand="false"
                :props="optionProps" style="width: 100%;" />
            </el-form-item>
            <el-form-item>
              <div style="justify-content: flex-end; margin-left:auto; margin-top: 30px;">
                <el-button @click=" drawer = false">取消</el-button>
                <el-button type="primary" @click="doAddJob">确认</el-button>
              </div>
            </el-form-item>
          </el-form>
        </div>
      </template>
    </el-drawer>
  </MainContainer>
</template>

<style scoped lang="less">
.main {
  min-height: 80vh;

  .left {
    border-right: 1px dashed #ccc;

    p {
      margin-left: 20px;
    }

    .search {
      padding: 10px 10px;
      width: 100%;
      border-radius: 10px;
    }

    .custom-tree-node {
      flex: 1;
      display: flex;
      align-items: center;
      justify-content: space-between;
      font-size: 14px;
      padding-right: 8px;
    }
  }

  .right {
    // border: 1px solid #ccc;

    .operate {
      display: flex;
      justify-content: space-between;
      align-items: center;
      padding: 10px 20px;

      .blank {
        flex: 1;
      }

      .op-list {
        display: flex;
        gap: 30px;



        a .el-icon {
          padding-right: 5px;
        }

      }
    }

    .pagination {
      display: flex;
      justify-content: end;
      margin-top: 20px;
      margin-right: 50px;
    }
  }
}
</style>
